//https://leetcode.cn/problems/generate-parentheses/?envType=study-plan-v2&envId=top-interview-150

class Solution {
public:
    void backtrace(vector<string>& ans, string& comb, int left, int right, int n) {
        if (comb.size() == 2 * n) {
            ans.push_back(comb);
            return;
        }

        if (left < n) {
            comb.push_back('(');
            backtrace(ans, comb, left + 1, right, n);
            comb.pop_back();
        } 
        if (right < left) {
            comb.push_back(')');
            backtrace(ans, comb, left, right + 1, n);
            comb.pop_back();
        }
    }

    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        string comb;
        backtrace(ans, comb, 0, 0, n);
        return ans;
    }
};